<?php

/** Cms_Resource_Product_Item */
if (!class_exists('Cms_Resource_Product_Item')) {
    require_once dirname(__FILE__) . '/Product/Item.php';
}

/**
 * Cms_Resource_Product
 * 
 * @category   Cms
 * @package    Cms_Model_Resource
 */
class Cms_Resource_Product extends BIS_Model_Resource_Db_Table_Abstract implements Cms_Resource_Product_Interface
{
    protected $_name    = 'product';
    protected $_primary  = 'productId';
    protected $_rowClass = 'Cms_Resource_Product_Item';
    
    /**
     * Get a product by its productId
     *
     * @param int $id The id to search for
     * @return Cms_Resource_Product_Item|null
     */
    public function getProductById($id)
    {
        return $this->find($id)->current();
    }
    
    /**
     * Get a list of product by their category
     *
     * @param  int|array $categoryId The category id(s)
     * @param array      $data  order, page, limit, search
     * @return Zend_Db_Table_Rowset|Zend_Paginator
     */
    public function getProductsByCategory($categoryId, $data= array())
    {
        $select = $this->select();
        
        $select->from(array('p'=>'product'), 
                        array('name'=>'p.name',
                              'category'=>'c.name',
                              'productId'=>'p.productId',
                              'categoryId'=>'p.categoryId',
                        	  'manufacturer'=>'p.manufacturer'
                            )
                )
               ->setIntegrityCheck(false)
               ->join(array('c'=>'category'), 'p.categoryId = c.categoryId', array('c.parentId'))
               ->where("p.categoryId IN(?)", $categoryId);
        
        if (isset($data['search'])) {
            $search = $data['search'];
            $select->where("p.name like ? OR c.name like ?", "%$search%");
        }
        
        if (isset($data['order'])) {
            $select->order($data['order']);
        }

	if (isset($data['page'])) {
		$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
		$paginator = new Zend_Paginator($adapter);
		$paginator->setItemCountPerPage($data['limit'])
	          	  ->setCurrentPageNumber((int) $data['page']);
		return $paginator;
	}

        return $this->fetchAll($select);
        
    } 
    
}